#ifndef INITDB_H
#define INITDB_H

#include <QtSql>



QSqlError addAps(const QString &essid, const QString &bssid, const QString &auth, const int power, const QVariant &crackIdx)
{
    QSqlQuery q;
    if (!q.prepare(QLatin1String("insert into aps(essid, bssid, auth, power, crack) values(?, ?, ?, ?, ?)")))
    {
        qDebug()<<"addAps error "<< q.lastError().text();
        return q.lastError();
    }
    q.addBindValue(essid);
    q.addBindValue(bssid);
    q.addBindValue(auth);
    q.addBindValue(power);
    q.addBindValue(crackIdx);
    q.exec();
    return QSqlError();
}

QSqlError delAps(const QString &essid)
{
    QSqlQuery q;
    if (!q.prepare(QLatin1String("delete from aps where essid = ?")))
    {
        qDebug()<<"addAps error "<< q.lastError().text();
        return q.lastError();
    }
    q.addBindValue(essid);
    q.exec();

    return QSqlError();
}

QVariant addCrack(const QString &essid, const QString &pwd, const QString &pin,
                  const QString &network, const QString &gw, const QString &ppoe = "",
                  const QString &ppoepwd = "")
{
    QSqlQuery q;
    if (!q.prepare(QLatin1String("insert into cracker(essid, password, pin, network, gateway, ppoe, ppoe_pwd) values(?, ?, ?, ? , ?, ?, ?)")))
    {
        qDebug()<<"addAps error "<< q.lastError().text();
        return -1;
    }
    q.addBindValue(essid);
    q.addBindValue(pwd);
    q.addBindValue(pin);
    q.addBindValue(network);
    q.addBindValue(gw);
    q.addBindValue(ppoe);
    q.addBindValue(ppoepwd);
    q.exec();
    return q.lastInsertId();
}

QVariant addClients(QSqlQuery &q, const QString &essid, const QString &client)
{
    q.addBindValue(essid);
    q.addBindValue(client);
    q.exec();
    return q.lastInsertId();
}

QSqlError initDb()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("wifidb.db");

    if (!db.open())
        return db.lastError();

    QStringList tables = db.tables();

    if (tables.contains("aps", Qt::CaseInsensitive))
        return QSqlError();

    QSqlQuery q;
    if (!q.exec(QLatin1String("create table aps(essid varchar primary key, bssid varchar, auth varchar, power integer)")))
        return q.lastError();
    if (!q.exec(QLatin1String("create table cracker(essid varchar primary key, password varchar, network varchar, gateway varchar, pin varchar, ppoe varchar, ppoe_pwd varchar)")))
        return q.lastError();
    if (!q.exec(QLatin1String("create table clients(essid varchar primary key, clients varchar)")))
        return q.lastError();


    return QSqlError();
}

#endif // INITDB_H
